#!/bin/bash

# 设置日志文件路径
LOG_FILE="/var/log/keepalived-check-ldap.log"

# 日志函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# 检查slapd进程
check_slapd() {
    ldapPid=$(pgrep -f '^slapd')
    if [ -z "$ldapPid" ]; then
        log_message "错误：LDAP服务（slapd）未运行"
        return 1
    fi
    
    # 检查进程是否真正响应
    if ! ps -p $ldapPid > /dev/null 2>&1; then
        log_message "错误：LDAP进程（PID: $ldapPid）存在但可能处于僵死状态"
        return 1
    fi
    
    log_message "LDAP服务正常运行（PID: $ldapPid）"
    return 0
}

# 主检查逻辑
if ! check_slapd; then
    log_message "正在停止Keepalived服务..."
    if ! systemctl stop keepalived; then
        log_message "错误：停止Keepalived服务失败"
    else
        log_message "已成功停止Keepalived服务"
    fi
    exit 1
fi

exit 0